package com.lucenten.collect.gnss.runnable.impl;

import cn.quevo.common.lang.BooleanUtils;
import cn.quevo.common.lang.StringUtils;
import com.lucenten.collect.gnss.entity.SatelliteStation;
import com.lucenten.collect.gnss.runnable.AbstractGnssUnZipRunService;
import com.lucenten.collect.gnss.runnable.GnssUnZipRunnable;
import com.lucenten.collect.gnss.service.ObsErvationService;
import com.lucenten.collect.gnss.service.SatelliteStationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通过站点来启动线程
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2019/5/16 10:58
 * @Copyright 湘豫（北京）科技有限公司版权所有.All Rights Reserved.
 */
@Slf4j
@Service("gnssUnZipRangeService")
public class GnssUnZipRangeServiceImpl extends AbstractGnssUnZipRunService {

    private Integer threadIndex = 0;
    private List<SatelliteStation> processList = null;
    @Resource(name = "satelliteStationService")
    private SatelliteStationService satelliteStationService;
    @Resource(name = "obsErvationService")
    private ObsErvationService obsErvationService;
    @Override
    protected void startThread(Path root) {
        try {
            log.info("BEGIN START："+root.toString());

            if (BooleanUtils.isTrue(this.getThreadStation().getLastYn()) || super.getThreadStation().getBegin() >= super.getSatelliteStationList().size() ) {
                processList = super.getSatelliteStationList().stream().limit(super.getThreadStation().getBegin()).skip(0).collect(Collectors.toList());
            }else {
                int end = super.getThreadStation().getBegin() + super.getThreadStation().getMaxSize();
                end = super.getSatelliteStationList().size() < end ? super.getSatelliteStationList().size() : end;
                processList = super.getSatelliteStationList().stream().limit(end).skip(super.getThreadStation().getBegin()).collect(Collectors.toList());
            }
            log.info("startThread SUM COUNT  " + processList.size()+"  END ");
            threadIndex = this.getThreadStation().getBegin();
            log.info("startThread threadIndex  " + threadIndex);
            /*Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    unzip(root, file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return super.postVisitDirectory(dir, exc);
                }
            });*/
            List<Path> files = Files.walk(root).filter(path -> !Files.isDirectory(path)).collect(Collectors.toList());
            for (Path p : files) {
                unzip(root, p);
            }
        } catch (IOException e) {
            log.error("文件遍历失败", e);
        }
    }

    private void unzip(Path root, Path file) {
        if (Files.notExists(file)) {
            return;
        }
        log.info("startThread UNZIP BEGIN  " );
        String fileName = file.getFileName().normalize().toString().toLowerCase();
        log.info("startThread fileName  " + fileName);
        // 如果不是.t02、.zip、d.z的格式则直接忽略
        if (!super.isProcess(file)) {
            return;
        }
        log.info("Thread RUN  " + fileName);
        // 陆态网或IGS数据
        if (fileName.endsWith("t02") || fileName.endsWith("d.z")) {
            if (!isExtProcess(fileName.endsWith("t02") ? "lutai" : "igs", fileName.substring(0, 4))) {
                return;
            }
        }else if (!isExtProcess(fileName.split("_")[3],"")){//GPS数据
            log.info("NOT FILE EXT "+fileName);
            return;
        }
        log.info("Thread RUN  NEXT");
        GnssUnZipRunnable runnable = GnssUnZipRunnable.builder().index(threadIndex++).root(root).file(file).stationMap(super.getStationMap())
                .reStationMap(super.getReStationMap()).satelliteStationService(satelliteStationService).obsErvationService(obsErvationService).build();
        fixedThreadPool.execute(runnable);
    }

    /**
     * 验证文件是否应该在此服务器处理
     *
     * @param stationId
     * @param stationName
     * @return
     */
    private boolean isExtProcess(String stationId, String stationName) {
        // 如果是最后一个处理服务器，则需要处理之前服务器都没有处理过的站点数据
        if (BooleanUtils.isTrue(super.getThreadStation().getLastYn())) {
            if (StringUtils.isBlank(stationName)) {
                return this.processList.stream().filter(station -> station.getStationId().equalsIgnoreCase(stationId)).count() <= 0;
            }
            return this.processList.stream().filter(station -> (station.getStationId().equalsIgnoreCase(stationId) && station.getStationName().equalsIgnoreCase(stationName))).count() <= 0;
        }
        if (StringUtils.isBlank(stationName)) {
            return this.processList.stream().filter(station -> station.getStationId().equalsIgnoreCase(stationId)).count() > 0;
        }
        return this.processList.stream().filter(station -> station.getStationId().equalsIgnoreCase(stationId) && station.getStationName().equalsIgnoreCase(stationName)).count() > 0;
    }
}
